package com.zhongxi.guoyuan.view.user;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.user.UploadResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.FileTool;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class UserInfoSettingActivity extends BaseActivity implements View.OnClickListener {

    private ImageView ivHead;
    private TextView tvStoreName;
    private RelativeLayout relaHead;
    private RelativeLayout relaName;
    private String img_path;
    private Bitmap bitmap;
    private String type;
    private EditText etSetName;
    private Map<String, String> map = new HashMap<String, String>();
    private RelativeLayout relaModifyPassword;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_user_info_setting);
        initTitle();
        tvTitle.setText("我的美容院设置");
        ivHead = (ImageView) findViewById(R.id.ivHead);
        tvStoreName = (TextView) findViewById(R.id.tvStoreName);
        relaHead = (RelativeLayout) findViewById(R.id.relaHead);
        relaName = (RelativeLayout) findViewById(R.id.relaName);
        relaModifyPassword = (RelativeLayout) findViewById(R.id.relaModifyPassword);
        if (null != MyApplication.getInstance().getShopName() && !"".equals(MyApplication.getInstance().getShopName())) {
            tvStoreName.setText(MyApplication.getInstance().getShopName());
        }
        if (null != MyApplication.getInstance().getAvatar() && !"".equals(MyApplication.getInstance().getAvatar())) {
            Glide.with(context).load(Url.BASE_URL+MyApplication.getInstance().getAvatar()).placeholder(R.mipmap.iv_eg).transform(new GlideRoundTransform(context, 20)).into(ivHead);
        }
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        relaHead.setOnClickListener(this);
        relaName.setOnClickListener(this);
        relaModifyPassword.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.relaHead:
                if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
                    //申请权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100);
                }else{
                    popHeadDialog();
                }
                break;
            case R.id.relaName:
                popNameDialog();
                break;
            case R.id.relaModifyPassword:
//                startAct(ModifyPasswordActivity.class);
                Intent intent = new Intent(context, ModifyPasswordActivity.class);
                intent.putExtra("position", 1);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        popHeadDialog();
    }

    /**
     * 弹出头像
     */
    private void popHeadDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_head_setting, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        dialog.getWindow().setContentView(layout);

        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView tvSelect = (TextView) layout.findViewById(R.id.tvSelect);
        TextView tvTakePhone = (TextView) layout.findViewById(R.id.tvTakePhone);
        tvSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPhoto();
                dialog.dismiss();
            }
        });
        tvTakePhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePhoto();
                dialog.dismiss();
            }
        });
    }

    private void getPhoto() {
        Intent intent = new Intent();
        /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
		/* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT);
		/* 取得相片后返回本画面 */
        startActivityForResult(intent, 1);
    }

    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(FileTool.getRootFilePath() + "head.jpg")));
        startActivityForResult(intent, 0);// 采用ForResult打开
    }

    /**
     * 弹出设置名称dialog
     */
    private void popNameDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_name_setting, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setView(layout);
        dialog.show();

        TextView tvComplete = (TextView) layout.findViewById(R.id.tvComplete);
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        etSetName = (EditText) layout.findViewById(R.id.etSetName);
        //取消
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        //设置名称
        tvComplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etSetName.getText().toString().trim())) {
                    showShortToast("名称不能为空!");
                } else {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("shopname", etSetName.getText().toString().trim());
                    type = "shopname";
                    getServer(Url.SET_SHOPNAME, map, "", false, null, "post");
                    dialog.dismiss();
                }
            }
        });
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
            if ("shopname".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                sharedPrefrences.edit().putString("shopname", etSetName.getText().toString().trim()).commit();
                tvStoreName.setText(etSetName.getText().toString().trim());
                showShortToast("设置店名成功！");
            }else if("uploadImg".equals(type)){
                UploadResult result = gson.fromJson(response, UploadResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if(null!=result.getAvatar()&&!"".equals(result.getAvatar())){
                    sharedPrefrences.edit().putString("avatar", result.getAvatar()).commit();
                    showShortToast("设置用户头像成功！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try{
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if(result.getCode() == 1000){
                showShortToast("上传头像失败，请检查网络是否良好！");
            }else if(result.getCode() == 1005){
                showShortToast("不是有效图片文件");
            }else if(result.getCode() == 1006){
                showShortToast("上传头像失败");
            }else if(result.getCode() == 1007){
                showShortToast("上传头像不能超过2M");
            }else if(result.getCode() == 1008){
                showShortToast("头像不是有效的图片文件");
            }else if(result.getCode() == 1009){
                showShortToast("头像存储失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {
                    img_path = FileTool.getRootFilePath() + "head.jpg";
                    try {
                        MediaStore.Images.Media.insertImage(getContentResolver(), img_path, "head", null);
                        File imageFile = new File(img_path);
                        startPhotoZoom(Uri.fromFile(imageFile), 150);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 1:
                if (resultCode == RESULT_OK) {
                    Uri imgUri = data.getData();
                    img_path = FileTool.getFilePath(context, imgUri);
                    if (img_path == null || img_path.equals("")) {
                        return;
                    }
                    File file = new File(img_path);
                    startPhotoZoom(Uri.fromFile(file), 150);
                }
                break;
            case 2:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        bitmap = extras.getParcelable("data");
                        try {
                            img_path = FileTool.getRootFilePath() + "head.jpg";
                            File file = new File(img_path);
                            if (file.exists()) {
                                file.delete();
                                file.exists();
                            } else {
                                file.exists();
                            }
                            FileOutputStream fOut = null;
                            try {
                                fOut = new FileOutputStream(file);
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                            ivHead.setImageBitmap(bitmap);
                            try {
                                fOut.flush();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                fOut.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            uploadHead(file);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
        }
    }

    /**
     * 用户上传头像
     *
     * @param absolutePath
     */
    private void uploadHead(File absolutePath) {
        try {
            type = "uploadImg";
            uploadServer(Url.UPLOAD_AVATAR, false, null, "file", absolutePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startPhotoZoom(Uri fromFile, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(fromFile, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", true);
        Bitmap.CompressFormat.JPEG.toString();
        startActivityForResult(intent, 2);
    }
}
